package projectmanagement.web;

import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import projectmanagement.model.Person;
import projectmanagement.model.Project;
import projectmanagement.model.Task;
import projectmanagement.util.ApplicationSecurityManager;
import projectmanager.model.dao.TaskDao;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class TaskListController implements Controller {

	private TaskDao taskManager;
	private ApplicationSecurityManager applicationSecurityManager;

	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		ModelAndView modelAndView = new ModelAndView("taskList");
		
		Person user = (Person)applicationSecurityManager.getPerson(request);
		
		List<Project> projects = new ArrayList<Project>();
		List<Task> tasks = null;
		
		if (user.getIsManager()){
			tasks = this.taskManager.getTaskList();

			for(int i = 0; i < tasks.size(); i++){
				if (!projects.contains(tasks.get(i).getProject())){
					projects.add(tasks.get(i).getProject());
				}
			}
		}else{
			tasks = this.taskManager.getTaskListByAssignee(user.getId());
			modelAndView.addObject("taskList", tasks);
			
			for(int i = 0; i < tasks.size(); i++){
				if (!projects.contains(tasks.get(i).getProject())){
					projects.add(tasks.get(i).getProject());
				}
			}
		}

		modelAndView.addObject("taskList", tasks);
		modelAndView.addObject("projectList", projects);

		return modelAndView;
	}

	public TaskDao getTaskManager() {
		return taskManager;
	}

	public void setTaskManager(TaskDao taskManager) {
		this.taskManager = taskManager;
	}

	public ApplicationSecurityManager getApplicationSecurityManager() {
		return applicationSecurityManager;
	}

	public void setApplicationSecurityManager(
			ApplicationSecurityManager applicationSecurityManager) {
		this.applicationSecurityManager = applicationSecurityManager;
	}

}